package com.neusoft.healthcity.config;



import com.neusoft.healthcity.config.scheduled.XmlGeneratorInfectious;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


@Component
public class ReadJsonConfig {

    /**
     * 返回zip文件下的所有json文件
     * @param zipPath zip文件所在目录
     * @param descDir 解压后文件的目录
     * @return
     * @throws IOException
     */
    public static List<String> unZipFiles(String zipPath,String descDir,long startTime,long endTime)throws IOException{
       return unZipFiles(new File(zipPath), descDir,startTime,endTime);
    }

    @SuppressWarnings("rawtypes")
    public static List<String> unZipFiles(File zipFile,String descDir,long startTime,long endTime)throws IOException{
        Logger logger = LoggerFactory.getLogger(ReadJsonConfig.class);
        logger.info("------定时任务开始读取当前指定目录中的zip文件-----");
        File pathFile = new File(descDir);

        //判断解压目录路径是否存在
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }
        //获取zip文件的集合
        File[] tempList = zipFile.listFiles();
        List<String> jsonFiles = new ArrayList<>();

        for (int i = 0; i < tempList.length; i++) {

            ZipFile zip = new ZipFile(tempList[i]);

            //获取zip文件的创建时间
            Path path1 =  tempList[i].toPath();
            BasicFileAttributes attr = Files.readAttributes(path1, BasicFileAttributes.class);
            Instant instant = attr.creationTime().toInstant();
            String format = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(instant);

            long fileTime = 0;
            try {
                fileTime = new SimpleDateFormat("yyyyMMddHHmmss").parse(format).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            logger.info("*****zip文件的创建时间"+fileTime+"*************");
            if((endTime !=0 && fileTime > startTime)
                    || (endTime !=0 && fileTime < endTime)
                    || (endTime==0 && fileTime > startTime)){
                continue;
            }


            //解压zip  返回ZIP文件条目的枚举
            for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zip.getInputStream(entry);
                String outPath = (descDir + zipEntryName).replaceAll("\\\\", "/");
                logger.info("——————————"+ outPath+"——————————");

                //判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if (!file.exists()) {
                    file.mkdirs();
                }

                //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if (new File(outPath).isDirectory()) {
                    continue;
                }

                //将json文件的位置保存
                jsonFiles.add(outPath);

                OutputStream out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[1024];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
                in.close();
                out.close();


            }
            logger.info("******************解压完毕********************");
        }
        return jsonFiles;
    }


    /**
     * 获取解压目录里面的所有文件
     * @param path
     * @param fileArrayList
     * @return
     */
    public  static ArrayList<File> getAllFile(String path, ArrayList<File> fileArrayList){
        boolean flag = false;
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if(tempList[i].isFile()){
                fileArrayList.add(tempList[i]);
            }

            if(tempList[i].isDirectory()){
                getAllFile(tempList[i].getAbsolutePath(),fileArrayList);
            }
        }
        return fileArrayList;
    }

    /**
     * 删除解压目录
     * @param path
     * @return
     */
    public static boolean deleteDir(File path){
        if(path.isDirectory()){
            String[] children = path.list();
            //递归删除文件
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(path, children[i]));
                if(!success){
                    return false;
                }
            }
        }
        return path.delete();
    }

}
